var hwtoken = getQueryString('hwtoken');

token = hwtoken;

hwDas.token = token;
hwDas.appinfo.callCode = callCode;
hwDas.appinfo.module = module;
hwDas.appinfo.system = system;

if (hwDas.hosts.length <= 0) {
    hwDas.hosts.push(hostsurl);
}
let nowIndex = -1;
let nowLayerIndex = -1;
let id = getQueryString('id');
// let title = decodeURIComponent(getQueryString('title'))
let c = getQueryString('c');
let r = getQueryString('r');

//存储当前展示的模块
let nowShowModule = [];
//存储树节点内容
let apptree;
let nowCheck = [];
let F = function(col, row) {
    if (this instanceof F) {
        let S = new this[col](row)
        return S
    } else {
        return new F(col, row)
    }
}


let div = `<div class='show-box'><a class='remove-title c-p'>清空</a></div>`;
let btn = `<a  class="d-b add-module align-center c-p" >添加模块</a>`;

// 通过输入的行列生成 行列
F.prototype = {
    0: function(row) {
        let html = [];
        return html;
    },
    1: function(row) {
        let html = [];

        if (row === 1) {
            html.push($(div).addClass('pw100').addClass('ph100'));
        } else if (row > 1) {
            for (let i = 0; i < row; i++) {
                html.push($(div).addClass('pw100').addClass('ph100').addClass('f-l'));
            }
        } else {
            html = [];
        }
        return html;
    },
    2: function(row) {
        let html = []
        if (row === 1) {
            for (let i = 0; i < 2; i++) {
                html.push($(div).addClass('pw100').addClass('ph50'));
            }
        } else if (row > 1) {
            for (let a = 0; a < 2; a++) {
                for (let i = 0; i < row; i++) {
                    html.push($(div).addClass('pw50').addClass('ph50').addClass('f-l'))
                }
            }
        } else {
            html = []
        }
        return html
    }
}


function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg); //获取url中"?"符后的字符串并正则匹配
    var context = "";
    if (r != null)
        context = r[2];
    reg = null;
    r = null;
    return context == null || context == "" || context == "undefined" ? "" : context;
}

// 递归快捷方式树
let moduleTreeFc = (data, pid) => {
    let treeArray = []
    for (var j = 0; j < data.length; j++) {
        if (data[j]["node_id"] == pid) {
            data[j]["parent_node_id"] = 0;
        }
        treeArray.push([data[j]["node_id"], data[j]["parent_node_id"] == "" ? 0 : data[j]["parent_node_id"], data[j]["node_name"]]);
    }
    return treeArray
}

// 定义tree
var tree = new dhtmlXTreeObject('SelectTree', '100%', '100%', 0);

//初始化tree
function initTree(treeObj) {
    treeObj.setSkin('dhx_web');
    treeObj.setImagePath("./lib/dhtmlx4.1/imgs/dhxtree_web/");
    treeObj.attachEvent("onClick", function(id) {
        let nowId = apptree.filter(x => x.node_id === id)
        $('.detail-text').html(nowId[0].node_desc)
        if (treeObj.isItemChecked(id)) {
            treeObj.setCheck(id, 0);
        } else {
            treeObj.setCheck(id, 1);
        }
    });
}

//检查id 是否在数组中
function checkId(arr, id) {
    let obj = {}
    for (var i = 0; i < arr.length; i++) {
        if (arr[i].id === id) {
            obj.flag = true
            obj.index = i
            break;
        } else {
            obj.flag = false;
            obj.index = -1
        }
    }
    return obj
}

//树形结构点击保存按钮
$('#ModuleSave').on('click', function() {
    let flag = true;
    let msg = '';
    let nowId = apptree.filter(x => x.node_id === tree.getSelectedItemId());
    if (nowId.length > 0) {
        if (nowId[0].node_type === "category") {
            flag = false;
            msg = '这是应用，请选择模块';
        } else {
            let checkHasId = nowCheck.filter(x => x.module_id === tree.getSelectedItemId())
            if (checkHasId.length > 0) {
                flag = false;
                msg = '不能重复选择模块';
            } else {
                flag = true;
                msg = '';
            }
        }
    }
    if (flag) {
        $('.add-module').eq(nowIndex).attr('data-id', tree.getSelectedItemId())
        $('.add-module').eq(nowIndex).html('').html(tree.getSelectedItemText())
        nowCheck.push({
            'module_id': tree.getSelectedItemId(),
            'module_name': tree.getSelectedItemText()
        })
        layer.close(nowLayerIndex);
    } else {
        alert(msg)
    }

});

//树形结构点击保存
$('#ModuleClose').on('click', function() {
    // if (parent && parent.layer) {
    layer.close(nowLayerIndex);
    // }
});

// 重置点击
$('body').on('click', '#reset', function() {
    let r = confirm("此操作将会清空当前选中模块，是否清空？")
    if (r === true) {
        nowCheck = []
        $('#col').val('');
        $('#row').val('');
        $('.g-box').html('');
    } else {

    }
})

// 清空的点击事件
$('body').on('click', '.remove-title', function() {
    let r_id = $(this).next().attr('data-id');
    let index = nowCheck.filter((x, i, s) => {
        if (x.module_id === r_id) {
            return i
        }
    })
    if (r_id !== undefined) {
        $(this).next().html('添加模块')
        $(this).next().attr('data-id', '');
        nowCheck.splice(index, 1);
    }


})


// 验证input输入值
$('input').on('blur', function() {
    let id = $(this).attr('id');
    if (id === "row") {
        let v = Number($(this).val())
        if (Number.isNaN(v)) {
            alert('请输入数字')
            $(this).val('')
            return false
        }
        if (v < 0 || v > 5) {
            alert('请输入大于0小于5的数字')
            $(this).val('')
            return false
        }
    } else {
        let v = Number($(this).val())
        if (Number.isNaN(v)) {
            alert('请输入数字')
            $(this).val('')
            return false
        }
        if (v < 0 || v > 2) {
            alert('请输入大于0小于2的数字')
            $(this).val('')
            return false
        }
    }

})


//点击保存生成行列
$("#sure").on('click', function() {
    let col = Number($('#col').val());
    let row = Number($('#row').val());
    if ((Number(c) !== 0 && col > 0) && (Number(r) !== 0 && row > 0)) {
        let r = confirm("此操作将会清空当前选中模块，是否清空？")
        if (r === true) {
            nowCheck = []
            let html = F(col, row)
            $('.g-box').html('');
            for (let i = 0; i < html.length; i++) {
                $(html[i]).append($(btn))
                $('.g-box').append($(html[i]))
            }
        } else {

        }
    } else {
        let html = F(col, row)
        $('.g-box').html('');
        for (let i = 0; i < html.length; i++) {
            $(html[i]).append($(btn))
            $('.g-box').append($(html[i]))
        }
    }
})

//点击保存，存入到数据库，并展示到工作台首页
$('#save').on('click', function() {
    let col = Number($('#col').val());
    let row = Number($('#row').val());
    let url = '/platform/v1/workTable/exhibitModule';
    let arr = []
    let workTableUrl = 'platform/v1/workTable/workTable';
    let layout = String(col) + String(row);
    let flag = true;
    for (var i = 0; i < $('.add-module').length; i++) {
        let Mid = $('.add-module').eq(i).attr('data-id');
        if (Mid === '') {
            alert('模块内容不能为空')
            flag = false;
            return false;
        }
        let params = {
            "worktableid": id,
            "mmoduleid": Mid,
            "exhibitno": i,
            "operationtype": 'insert'
        }
        arr.push(params);
    }

    let worktableid = id
    hwDas.del(url, {}, { worktableid: worktableid }, function(result) {
        hwDas.save(workTableUrl, {}, {}, { worktableid: worktableid, layoutstyle: layout, "operationtype": 'update' }, function(result) {
            if (!!result.isSucceed) {
                hwDas.save(url, {}, {}, arr, function(result) {
                    if (!!result.isSucceed) {
                        alert('保存成功');
                        top.pt.resfreshTab('工作台');
                        top.pt.closeTab('模块添加');
                    } else {
                        alert('保存失败');
                    }
                })
            } else {
                alert('保存失败');
            }
        })
    }, () => {
        alert('系统异常，请稍后重试');
    });
})

// 取消事件
$('body').on('click', '#cancel', function() {
    top.pt.closeTab('模块添加')
})


$(document).on('click', '.add-module', function() {
    nowIndex = $('.add-module').index($(this))
    nowLayerIndex = layer.open({
        type: 1,
        shade: [0],
        area: ['100%', '100%'],
        anim: 2,
        maxmin: true, //开启最大化最小化按钮
        resize: true,
        content: $('#select'),
        title: '选择模块',
        shadeClose: false,
        moveOut: true,
        closeBtn: 1,
        scrollbar: true,
        zIndex: 100,
        success: function() {},
        end: function() {}
    })
})


$(function() {
    initTree(tree)
    $('#row').val(r)
    $('#col').val(c)
    hwDas.get('/platform/v1/workTable/exhibitModule', {}, {}, (data) => {
        nowCheck = data.data[0].datas;
        let html = F(Number(c), Number(r));
        $('.g-box').html('');
        for (let i = 0; i < html.length; i++) {
            $(html[i]).append($(btn));
            $('.g-box').append($(html[i]));
        }
        for (let i = 0; i < nowCheck.length; i++) {
            $('.show-box').eq(i).find('.add-module').html(nowCheck[i].module_name).attr('data-id', nowCheck[i].module_id);
        }
    }, (e) => {

        alert('获取数据失败');
    }, "json")

    hwDas.get('/platform/v1/desktopTree', {}, { "desktopid": "80c97de0-1cad-4101-87d2-2eade9320df8" }, (data) => {
        apptree = data.data[0].datas;
        let list = moduleTreeFc(data.data[0].datas, "0");
        tree.loadJSArray(list);
    }, (e) => {
        alert('获取数据失败')
    }, "json")
    hwDas.get('platform/v1/workTable/exhibitModule', {}, {}, (data) => {}, (e) => {
        alert('获取数据失败')
    }, "json")
})